package com.ejemplo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESEncrypt {
	
	private final String ALGORITMO = "AES";//algoritmo (si cambia la imprementacion tambien)
	private final int LONGITUD = 128;//longitud de la llave ()
	private final String CODIFICACION = "UTF-8";//como se convertira a byte, esto sera mas adelante
	
//	private AESKey aesKey;
	
	private String key;
	
	
	
//	public AESEncrypt(AESKey aesKey){
//		this.aesKey = aesKey;
//	}
	
	public AESEncrypt() throws Exception{
//		generaKey();
		recuperarKey();
	}
	
	private void recuperarKey() throws IOException{
//		InputStream is = AESEncrypt.class.getResourceAsStream("key.txt");
		File file = new File("key.txt");
		BufferedReader entrada = new BufferedReader( new FileReader( file ) );
		key = entrada.readLine();
		System.out.println("Lectura correcta del archivo!");
		System.out.println("Key : " + key); 
	}
	
	private void generaKey() throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance(ALGORITMO);
		kgen.init(LONGITUD);
		SecretKey skey = kgen.generateKey(); 
		key = HexToString(skey.getEncoded());
		
		File file = new File("key.txt");
		file.mkdir();
		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
		bw.write(key);
		System.out.println("Se genero el archivo!");
		System.out.println("Key : " + key);
		bw.close();
		
	}

	public String encripta(String cadena) 
	  throws NoSuchAlgorithmException,
	  NoSuchPaddingException, InvalidKeyException,
	  IllegalBlockSizeException, BadPaddingException,
	  UnsupportedEncodingException 
	{  
	  byte[] raw = StringToHex(key);
	  SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITMO);
	  Cipher cipher = Cipher.getInstance(ALGORITMO);
	  cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
	  byte[] encrypted = cipher.doFinal(cadena.getBytes(CODIFICACION));
	  String encriptado = HexToString(encrypted);
	  return encriptado;
	}
	
	private String HexToString(byte[] arregloEncriptado) {
		String textoEncriptado = "";
		for (int i = 0; i < arregloEncriptado.length; i++) {
			int aux = arregloEncriptado[i] & 0xff;
			if (aux < 16) {
				textoEncriptado = textoEncriptado.concat("0");
			}
			textoEncriptado = textoEncriptado.concat(Integer.toHexString(aux));
		}
		return textoEncriptado;
	}

	private byte[] StringToHex(String encriptado) {
		byte[] enBytes = new byte[encriptado.length() / 2];
		for (int i = 0; i < enBytes.length; i++) {
			int index = i * 2;
			String aux = encriptado.substring(index, index + 2);
			int v = Integer.parseInt(aux, 16);
			enBytes[i] = (byte) v;
		}
		return enBytes;
	}
	
	public String desencriptar(String encriptado) throws InvalidKeyException,
	  IllegalBlockSizeException, BadPaddingException,
	  UnsupportedEncodingException, NoSuchAlgorithmException,
	  NoSuchPaddingException 
	{
	 byte[] raw = StringToHex(key);
	 SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITMO);
	 Cipher cipher = Cipher.getInstance(ALGORITMO);  
	 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
	 byte[] original = cipher.doFinal(StringToHex(encriptado));
	 String originalString = new String(original);
	 return originalString;
	}

	public String getKey(){
		return key;
	}
}
